import uuid
import logging
import datetime

from base.connection import get_db_session
from conf import config
from helper.user import UserHelper

logger = logging.getLogger("wechat.helper.register_help")


def register(open_id, password, parent_agency_id, parent_uid, type=0, sub_type=0):
    logger.info(f"gift_register: open_id={open_id}")
    class User(object):
        pass

    class Agency(object):
        pass

    class UserAgency(object):
        pass

    session = get_db_session([
        {"db_table": "ebt_user", "model": User},
        {"db_table": "ebt_agency", "model": Agency},
        {"db_table": "ebt_user_agency", "model": UserAgency},
    ])
    agency_uid = str(uuid.uuid1())
    user = session.query(User).filter_by(ebf_user_id=open_id).first()
    ua = session.query(UserAgency).filter_by(ebf_ua_bind_user_id=open_id).first()
    career_agency = UserHelper.get_career_agency(parent_uid)
    career_agency_uid = career_agency.ebf_agency_uid if career_agency else config.DEFAULT_AGENCY_UID
    parent_agency = session.query(Agency).filter_by(ebf_agency_id=parent_agency_id).first()
    depth = parent_agency.ebf_agency_depth + 1 if parent_agency else 1
    if ua:
        session.close()
        return True

    try:
        agency = Agency()
        agency.ebf_agency_name = user.ebf_user_nickname
        agency.ebf_agency_uid = agency_uid
        agency.ebf_factory_id = config.FACTORY_ID
        agency.ebf_agency_parent_id = parent_agency_id
        agency.ebf_agency_type = type
        agency.ebf_agency_sub_type = sub_type
        agency.ebf_agency_career_uid = career_agency_uid
        agency.ebf_agency_invite_uid = parent_uid
        agency.ebf_agency_depth = depth
        session.add(agency)
        session.flush() # 此处flush不能省略, 下面用到agency_id

        id = str(agency.ebf_agency_id)
        new_user = User()
        new_user.ebf_user_id = "P" + id
        new_user.ebf_user_password = password
        new_user.user_create_date = datetime.datetime.utcnow()
        new_user.ebf_user_nickname = user.ebf_user_nickname
        new_user.ebf_user_factory_id = config.FACTORY_ID
        new_user.ebf_user_type = 3
        new_user.ebf_user_gender = user.ebf_user_gender
        user.ebf_user_agency_uid = agency_uid
        session.add(new_user)
        session.flush() # 此处flush不能省略, 因下面user_agency记录需要new_user记录中的外键约束new_user.ebf_user_id

        user_agency = UserAgency()
        user_agency.ebf_user_id = "P" + id
        user_agency.ebf_agency_id = agency.ebf_agency_id
        user_agency.ebf_ua_bind_user_id = open_id
        session.add(user_agency)
        session.commit()
        session.close()
    except Exception as e:
        logger.error(f"err={e}, open_id={open_id}")
        session.rollback()
        session.close()
        return False
    return True